<?php

class NewsResource extends Resource
{
    const TTL = NEWS_UPDATE_PERIOD;
    const ID = "news";

    public function GetId()
    {
        return self::ID;
    }

    public function GetTTL()
    {
        return self::TTL;
    }

    public function GetFreshData()
    {
        $news = NewsResource::GetRSSFromBlog();

        if ( empty($news) )
        {
            $news = array();
        }
        else
        {
            $lastNews = $news[0];
            Core::SetProperty('last_news_hash', sha1($lastNews->link));
        }

        Core::SetProperty('news_count', count($news));
        return $news;
    }

    /**
     * Returns rss from blog.
     *
     * @return array
     */
    public static function GetRSSFromBlog()
    {
        $rss = @file_get_contents( NEWS_BLOG_RSS_URL );
        $news = RSSParser::Parse($rss);

        return $news;
    }

    /**
     *
     */
    public static function GetNewsBySlug($url)
    {
        $news = NewsResource::GetRSSFromBlog();
        $lastNews = '';

        if ( empty($news) )
        {
            $lastNews = array();
        }
        else
        {
            foreach ($news as $item)
            {
                if (stripos($item->link, $url))
                {
                    $lastNews = $item;
                    break;
                }
            }
            if (empty($lastNews))
            {
                $lastNews = $news[0];
            }
        }

        $lastNews->date = DateUtils::FormatDateToFullWithYear($lastNews->date);
        return $lastNews;
    }

    public static function GetLastPostFromBlog()
    {
        $posts = self::GetRSSFromBlog();

        if ( is_null($posts) || empty($posts))
        {
            return new NewsItem();
        }

        $lastNews = $posts[0];
        $lastNews->date = DateUtils::FormatDateToFullWithYear($lastNews->date);
        return $lastNews;
    }
}